const apiMethods = {
  methods: {
   
    apiGet(url, data) {
      return new Promise((resolve, reject) => {
        axios.get(url, data).then((response) => {
          resolve(response.data)
        }, (response) => {
          reject(response)
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
        })
      })
    },
    apiPost(url, data) {
      return new Promise((resolve, reject) => {
        axios.post(url, data).then((response) => {
          resolve(response.data)
        }).catch((response) => {

          reject(response)
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
        })
      })
    },
    //下载 
    download(url,data){
      const ab2str = (u,f) => {
           var b = new Blob([u]);
           var r = new FileReader();
            r.readAsText(b, 'utf-8');
            r.onload = function (){if(f)f.call(null,r.result)}
      }
      const str2ab = (s,f) => {
            var b = new Blob([s],{type:'text/plain'});
            var r = new FileReader();
            r.readAsArrayBuffer(b);
            r.onload = function (){if(f)f.call(null,r.result)}
      }
      return new Promise((resolve,reject) => {
        
          axios.post(url, data ,{responseType: 'blob'}).then(response=>{
              const content = response.data;
              let reader = new FileReader();
              reader.readAsArrayBuffer(content.slice(0,1));
              reader.onload = evt => {  
                  if(evt.target.readyState == FileReader.DONE){  
                    const buffer = evt.target.result; 
                    var dv = new DataView(buffer);
                    //从第1个字节读取一个8位无符号整数
                    var clen = dv.getUint8(0);
                    ab2str(content.slice(1,clen +1),title=>{
                        const blob = new Blob([content.slice(clen +1,content.size)]);
                        const fileName = title + ".xls";
                        resolve(title ,blob);
                        if ('download' in document.createElement('a')) { // 非IE下载
                          const elink = document.createElement('a')
                          elink.download = fileName
                          elink.style.display = 'none'
                          elink.href = URL.createObjectURL(blob)
                          document.body.appendChild(elink)
                          elink.click()
                          URL.revokeObjectURL(elink.href) // 释放URL 对象
                          document.body.removeChild(elink)
                        } else { // IE10+下载
                          navigator.msSaveBlob(blob, fileName)
                        }
                    });
                  }
                  
              }
          }).catch(function(error) {
              console.log(error);
              _g.toastMsg('warning', '下载失败');
              reject(error);
          });

      });
      
    },
    //上传功能
    apiPostForm(url , data) {
      let getPropertyLen = (obj={}) => {
        let index = 0;
        for(let p in obj){
          if(obj.hasOwnProperty(p)) {
            index++;
          }
        }
        return index;
      }
      return new Promise((resolve, reject) => {
        // let config = {headers: {'Content-Type':'multipart/form-data'}};
        let _data = {},logData = {};
        if(data){
          _data = new FormData();
          for(let p in data){
            if(Array.isArray(data[p])){
              if(data[p].length>0 && getPropertyLen(data[p][0])>0){
                  for(let i=0;i<data[p].length;i++){
                      for(let p1 in data[p][i]){
                          let key = `${p}[${i}].${p1}`;
                          let value = data[p][i][p1];
                          if(!value){
                              value = "";
                          }
                          logData[key] = value;
                          _data.append(key,value)    
                      }
                  }
              }
            }else{
              logData[p] = data[p]?data[p]:"";
              _data.append(p , data[p]?data[p]:"");
            }
          }
        }
        console.log('logData',logData);
        logData = {};
        // axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
        axios.post(url, _data).then((response) => {
          resolve(response.data)
        }).catch((response) => {
          reject(response)
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
        })
      })
    },
    apiDelete(url, id) {
      return new Promise((resolve, reject) => {
        axios.delete(url + '?id=' + id).then((response) => {
          resolve(response.data)
        }, (response) => {
          reject(response)
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
        })
      })
    },
    apiWorkDelete(url, data) {
      return new Promise((resolve, reject) => {
        axios.delete(url, data).then((response) => {
          resolve(response.data)
        }, (response) => {
          reject(response)
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
        })
      })
    },
    apiPut(url, id, obj) {
      return new Promise((resolve, reject) => {
        axios.put(url + id, obj).then((response) => {
          resolve(response.data)
        }, (response) => {
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
          reject(response)
        })
      })
    },
    handelResponse(res, cb, errCb) {
      _g.closeGlobalLoading()
      if (res.code == 200) {
        cb(res.data)
      } else {
        if (typeof errCb == 'function') {
          errCb()
        }
        this.handleError(res)
      }
    },
    handleError(res) {
      if (res.code) {
        switch (res.code) {
          case 101:
            console.log('cookie = ', Cookies.get('rememberPwd'))
            if (Cookies.get('rememberPwd')) {
              let data = {
                rememberKey: Lockr.get('rememberKey')
              }
              this.reAjax('admin/base/relogin', data).then((res) => {
                this.handelResponse(res, (data) => {
                  this.resetCommonData(data)
                })
              })
            } else {
              _g.toastMsg('error', res.message || res.obj || res.msg)
              setTimeout(() => {
                router.replace('/')
              }, 1500)
            }
            break
          case 103:
            _g.toastMsg('error', res.message || res.obj || res.msg)
            setTimeout(() => {
              router.replace('/')
            }, 1500)
            break
          // case 400:
          //   this.goback()
          //   break
          default:
            _g.toastMsg('error', res.message || res.obj || res.msg)
        }
      } else {
        console.log('default error')
      }
    },
    resetCommonData(data) {
      _(data.menusList).forEach((res, key) => {
        if (key == 0) {
          res.selected = true
        } else {
          res.selected = false
        }
      })
      Lockr.set('menus', data.privilegeVOS)              // 菜单数据
      Lockr.set('token', data.token)              // 权限认证
      // Lockr.set('rememberKey', data.rememberKey)      // 记住密码的加密字符串
      // Lockr.set('authList', data.authList)            // 权限节点列表
      Lockr.set('userInfo', data)            // 用户信息
      // Lockr.set('sessionId', data.sessionId)          // 用户sessionid
      window.axios.defaults.headers.token = Lockr.get('token')
      // let routerUrl = ''
      // if (data.menusList[0].url) {
      //   routerUrl = data.menusList[0].url
      // } else {
      //   routerUrl = data.menusList[0].child[0].child[0].url
      // }
      // setTimeout(() => {
      //   let path = this.$route.path
      //   if (routerUrl != path) {
      //     router.replace(routerUrl)
      //   } else {
      //     _g.shallowRefresh(this.$route.name)
      //   }
      // }, 1000)
    },
    reAjax(url, data) {
      return new Promise((resolve, reject) => {
        axios.post(url, data).then((response) => {
          resolve(response.data)
        }, (response) => {
          reject(response)
          _g.closeGlobalLoading()
          _g.toastMsg('warning', '请求超时，请检查网络');
        })
      })
    }
  },
  computed: {
    showLoading() {
      return store.state.globalLoading
    }
  }
}

export default apiMethods
